package com.changgou.filter;

import com.changgou.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;


@Component
public class AUthorizeFilter implements GlobalFilter, Ordered {

    @Autowired
    private AuthService authService;

    @Autowired
    private URLFilter urlFilter;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    private final String LOGIN_UTL="/api/oauth/toLogin";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //

        //或取当前请求响应对象
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        //判断当前是否是登录请求
        //判断cookie中是否存在信息，没有的话拒绝访问
        String jit = authService.getJitFromCookie(request);
        if (StringUtils.isEmpty(jit)){
            //判断跳转
           return this.toLocation(LOGIN_UTL+"?from="+request.getURI(),exchange,chain);
        }
        //判断redis中是否有令牌存在没有的话拒绝访问
        String redisToken = authService.getTokenFromRedisByJit(jit);
        if(StringUtils.isEmpty(redisToken)){
            //判断跳转
            return this.toLocation(LOGIN_UTL+"?from="+request.getURI(),exchange,chain);
        }
        request.mutate().header("Authorization","Bearer "+redisToken);
        return chain.filter(exchange);
    }

    private Mono<Void> toLocation(String login_utl, ServerWebExchange exchange,GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        if(!urlFilter.hasAuthorize(path)){  //判断是否是需要权限的地址
            return chain.filter(exchange);
        }
        ServiceInstance sysgateway = loadBalancerClient.choose("GATEWAY-WEB");
        URI uri = sysgateway.getUri();
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.SEE_OTHER);
        response.getHeaders().set("Location","http://192.168.16.172:8001"+login_utl);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
